package com.wsyu.springbootbackend.core.util;

import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class HttpServletUtils {

    public static void writeJsonResponse(HttpServletResponse response, HttpStatus status, String jsonBody) throws IOException {
        response.setStatus(status.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        PrintWriter printWriter = response.getWriter();
        printWriter.print(jsonBody);
        printWriter.flush();
        printWriter.close();
    }

    public static boolean isJsonContentType(HttpServletRequest request) {
        // 获取Content-Type请求头
        String contentType = request.getContentType();

        // 处理Content-Type可能为null的情况
        if (contentType == null) {
            return false;
        }

        // 处理可能包含字符编码的情况，如"application/json;charset=UTF-8"
        String[] parts = contentType.split(";");
        String mimeType = parts[0].trim();
        System.out.println("|" + mimeType + "|");

        // 判断MIME类型是否为application/json
        return "application/json".equals(mimeType);
    }

    @SneakyThrows
    public static String getJsonBody(HttpServletRequest request) {
        BufferedReader br = request.getReader();

        String str;
        StringBuilder wholeStr = new StringBuilder();
        while ((str = br.readLine()) != null) {
            wholeStr.append(str);
        }
        return wholeStr.toString();
    }
}